import datetime
import logging
import logging.handlers
import os
import json
from enum import Enum

# Global variable to control console log level
_CONSOLE_LOG_LEVEL = logging.INFO
# Keep track of all created loggers to update their console handlers
_ALL_LOGGERS = []

def set_console_log_level(level):
    """
    Set the console log level for all loggers.
    
    :param level: Logging level (e.g., logging.DEBUG, logging.INFO)
    """
    global _CONSOLE_LOG_LEVEL
    _CONSOLE_LOG_LEVEL = level
    
    # Update console handler level for all existing loggers
    for logger_instance in _ALL_LOGGERS:
        for handler in logger_instance.logger.handlers:
            if isinstance(handler, logging.StreamHandler):
                handler.setLevel(_CONSOLE_LOG_LEVEL)

class LogLevel(Enum):
    DEBUG = "调试"
    INFO = "提示"
    WARNING = "警告"
    ERROR = "错误"
    OTHER = "其它"

class RotatingFileHandler(logging.handlers.RotatingFileHandler):
    """自定义循环文件处理器，实现按序号循环覆盖"""
    
    def __init__(self, filename, maxBytes=0, backupCount=0, encoding=None, delay=False):
        """
        初始化循环文件处理器
        Args:
            filename: 日志文件名模式
            maxBytes: 单个日志文件最大字节数
            backupCount: 保留的日志文件数量
        """
        self.baseFilename = filename
        self.maxBytes = maxBytes
        self.backupCount = backupCount
        super().__init__(filename, maxBytes=maxBytes, backupCount=backupCount, encoding=encoding, delay=delay)
        
    def doRollover(self):
        """
        执行日志文件滚动（覆盖而不是追加序号）
        """
        if self.stream:
            self.stream.close()
            self.stream = None
            
        # 删除最旧的文件（如果存在）
        if self.backupCount > 0:
            for i in range(self.backupCount - 1, 0, -1):
                sfn = f"{self.baseFilename}.{i}"
                dfn = f"{self.baseFilename}.{i-1}" if i > 1 else self.baseFilename
                if os.path.exists(sfn):
                    if os.path.exists(dfn):
                        os.remove(dfn)
                    os.rename(sfn, dfn)
                    
        # 创建新文件
        if not self.delay:
            self.stream = self._open()
            
class Logger:
    def __init__(self, module_name):
        self.module_name = module_name
        self.logger = logging.getLogger(module_name)
        
        # Add this logger to the global list
        _ALL_LOGGERS.append(self)
        
        # 配置日志记录器（如果尚未配置）
        if not self.logger.handlers:
            self._setup_logger()

    def _setup_logger(self):
        """设置日志记录器"""
        # 创建日志目录（如果不存在）
        log_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
            
        # 生成带时间戳和序号的日志文件名
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        log_filename = os.path.join(log_dir, f"recode_{timestamp}_0.log")
        
        # 创建自定义循环文件处理器
        # 限制单个文件大小为1MB，保留5个文件
        file_handler = RotatingFileHandler(
            log_filename,
            maxBytes=1024*1024,  # 1MB
            backupCount=5
        )
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        
        # 设置日志格式
        formatter = logging.Formatter("[%(levelname)s] [%(asctime)s] [%(name)s] [%(message)s]\r", 
                                    datefmt="%Y/%m/%d-%H:%M:%S")
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # Set console log level based on global setting
        console_handler.setLevel(_CONSOLE_LOG_LEVEL)
        
        # 文件处理器始终记录DEBUG及以上级别的日志
        file_handler.setLevel(logging.DEBUG)
        
        # 添加处理器到记录器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
        # 设置日志级别为DEBUG，输出所有级别的日志
        self.logger.setLevel(logging.DEBUG)

    def _format_message(self, level, message):
        timestamp = datetime.datetime.now().strftime("%Y/%m/%d-%H:%M:%S")
        return f"[{level.value}] [{timestamp}] [{self.module_name}] [{message}]"

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

    def other(self, message):
        self.logger.info(f"[其它] {message}")

def get_logger(module_name):
    """获取日志记录器实例"""
    return Logger(module_name)